/*
 * Powered By dico
 * Since 2017 - 2018
 */
package com.seeyoui.kensite.bussiness.exam.questionImport.controller;

import java.io.File;
import java.sql.*;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.poi.ss.usermodel.Row;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.seeyoui.kensite.common.util.DateUtils;
import com.seeyoui.kensite.common.util.StringUtils;
import com.seeyoui.kensite.common.constants.StringConstant;
import com.seeyoui.kensite.common.base.domain.EasyUIDataGrid;
import com.seeyoui.kensite.common.base.controller.BaseController;
import com.seeyoui.kensite.common.util.RequestResponseUtil;
import com.seeyoui.kensite.common.util.excel.ExcelUtil;
import com.seeyoui.kensite.common.util.excel.ExportExcel;

import org.apache.lucene.index.Term;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import com.seeyoui.kensite.common.base.domain.Page;
import com.seeyoui.kensite.framework.luence.domain.LuceneDocument;
import com.seeyoui.kensite.framework.luence.util.LuceneUtils;
import com.seeyoui.kensite.bussiness.exam.common.Const;
import com.seeyoui.kensite.bussiness.exam.question.domain.Question;
import com.seeyoui.kensite.bussiness.exam.question.service.QuestionService;
import com.seeyoui.kensite.bussiness.exam.questionImport.domain.QuestionDto;
import com.seeyoui.kensite.bussiness.exam.questionImport.domain.QuestionImport;
import com.seeyoui.kensite.bussiness.exam.questionImport.service.QuestionImportService;
import com.seeyoui.kensite.bussiness.exam.questionImport.util.AnalyticalExcel;
import com.seeyoui.kensite.bussiness.exam.questionOption.domain.QuestionOption;
import com.seeyoui.kensite.bussiness.exam.questionOption.service.QuestionOptionService;

/**
 * QuestionImport
 * 
 * @author dico
 * @version 2.0
 * @since 1.0
 * @date 2018-01-07
 */

@Controller
@RequestMapping(value = "exam/questionImport")
public class QuestionImportController extends BaseController {

    @Autowired
    private QuestionImportService questionImportService;

    @Autowired
    private QuestionService questionService;
    @Autowired
    private QuestionOptionService optionService;

    /**
     * 展示列表页面
     * 
     * @param modelMap
     * @param module
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("exam:questionImport:view")
    @RequestMapping(value = "/{page}")
    public ModelAndView view(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            @PathVariable String page) throws Exception {
        return new ModelAndView("bussiness/exam/questionImport/" + page, modelMap);
    }

    /**
     * 根据ID查询单条数据
     * 
     * @param modelMap
     * @param module
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("exam:questionImport:select")
    @RequestMapping(value = "/data/{id}")
    @ResponseBody
    public Object data(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, @PathVariable String id)
            throws Exception {
        QuestionImport questionImport = questionImportService.findOne(id);
        return questionImport;
    }

    /**
     * 根据ID查询单条数据并返回相应表单
     * 
     * @param modelMap
     * @param module
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("exam:questionImport:view")
    @RequestMapping(value = "/form/{page}/{id}")
    public ModelAndView form(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            @PathVariable String page, @PathVariable String id) throws Exception {
        QuestionImport questionImport = questionImportService.findOne(id);
        modelMap.put("questionImport", questionImport);
        return new ModelAndView("bussiness/exam/questionImport/" + page, modelMap);
    }

    /**
     * 获取列表展示数据
     * 
     * @param modelMap
     * @param questionImport
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("exam:questionImport:select")
    @RequestMapping(value = "/list/data", method = RequestMethod.POST)
    @ResponseBody
    public Object listData(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            QuestionImport questionImport) throws Exception {
        List<QuestionImport> questionImportList = questionImportService.findList(questionImport);
        int total = questionImportService.findTotal(questionImport);
        EasyUIDataGrid eudg = new EasyUIDataGrid();
        eudg.setTotal(String.valueOf(total));
        eudg.setRows(questionImportList);
        return eudg;
    }

    /**
     * 获取列表展示数据带分页器用于jsp自己做分页
     * 
     * @param modelMap
     * @param questionImport
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("exam:questionImport:view")
    @RequestMapping(value = "/list/page", method = RequestMethod.POST)
    @ResponseBody
    public Object listPage(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            QuestionImport questionImport) throws Exception {
        List<QuestionImport> questionImportList = questionImportService.findList(questionImport);
        int total = questionImportService.findTotal(questionImport);
        Page<QuestionImport> page = new Page<QuestionImport>(questionImport.getPage(), questionImport.getRows(), total);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("rows", questionImportList);
        dataMap.put("page", page);
        return dataMap;
    }

    /**
     * 获取所有数据
     * 
     * @param modelMap
     * @param questionImport
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("exam:questionImport:select")
    @RequestMapping(value = "/list/all", method = RequestMethod.POST)
    @ResponseBody
    public Object listAll(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            QuestionImport questionImport) throws Exception {
        List<QuestionImport> questionImportList = questionImportService.findAll(questionImport);
        return questionImportList;
    }

    /**
     * 保存新增的数据
     * 
     * @param modelMap
     * @param questionImport
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("exam:questionImport:insert")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public String save(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, QuestionImport questionImport)
            throws Exception {
        if (!beanValidator(modelMap, questionImport)) {
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }

        String libraryId = questionImport.getLibraryId();

        // 读取模板地址
        String uri = questionImport.getFilePath();
        // 获取模板绝对位置
        String catalinaHome = System.getProperty("catalina.home");
        if (!catalinaHome.endsWith(File.separator)) {
            catalinaHome += File.separator;
        }
        String STORAGE_DIR = catalinaHome + "webapps" + File.separator + "docs" + File.separator;
        // String address =
        // request.getSession().getServletContext().getRealPath(uri);
        String address = STORAGE_DIR + "/" + uri;
        if (address != null) {
            File file = new File(address);
            // FileInputStream in_file = new FileInputStream(files);

            // 导入模板
            // 返回消息
            String Msg = null;
            // 获取试题信息是否为空
            boolean isQuestion = false;

            // 获取文件名
            // String name = file.getOriginalFilename();
            String name = file.getName();

            // 进一步判断文件是否为空（即判断其大小是否为0或其名称是否为null）验证文件名是否合格
            // long size = file.getSize();
            long size = file.length();
            if (name == null || ("").equals(name) && size == 0 && !ExcelUtil.validateExcel(name)) {
                Msg = "文件格式不正确！请使用.xls或.xlsx后缀文档。";
                request.getSession().setAttribute("msg", Msg);
                return null;
            }

            // 创建处理EXCEL
            AnalyticalExcel readExcel = new AnalyticalExcel();
            // 解析excel，获取试题信息集合。
            List<QuestionDto> excelInfo = readExcel.getExcelProductModelInfo(file);

            if (excelInfo != null && !excelInfo.toString().equals("[]") && excelInfo.size() >= 1) {
                isQuestion = true;
            }

            if (isQuestion) {

                boolean isPass = readExcel.isTo(excelInfo);
                // 通过校验
                if (isPass) {

                    // List<QuestionType> types = typeService.findAllList();
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    // for (QuestionType questionType2 : types) {
                    // map.put(questionType2.getName(), questionType2.getId());
                    // }

                    for (int i = 0; i < excelInfo.size(); i++) {
                        int k = i + 2;
                        QuestionDto productModelDto = excelInfo.get(i);

                        // 设置商品表对象
                        Question product = new Question();
                        /*
                         * if (productModelDto.getName() != null) {
                         * product.setName(productModelDto.getName()); }
                         */
                        if (productModelDto.getContent() != null) {
                            product.setContent(productModelDto.getContent());
                        }

                        // 处理试题类型
                        if (productModelDto.getQuestionTypeId() != null) {
                            if ("单选题".equals(productModelDto.getQuestionTypeId())) {
                                String string = Const.QUESTION_TYPE_ID_SINGLE;
                                product.setQuestionTypeId(string);
                            }
                            if ("多选题".equals(productModelDto.getQuestionTypeId())) {
                                product.setQuestionTypeId(Const.QUESTION_TYPE_ID_MULTIPLE);
                            }
                            if ("判断题".equals(productModelDto.getQuestionTypeId())) {
                                product.setQuestionTypeId(Const.QUESTION_TYPE_ID_JUDGE.intern());
                            }

                        }

                        if (productModelDto.getAnalysis() != null) {
                            product.setAnalysis(productModelDto.getAnalysis());
                        }

                        if (productModelDto.getAnswer() != null) {
                            product.setAnswer(productModelDto.getAnswer());
                        }

                        product.setLibraryId(libraryId);
                        List<QuestionOption> options = new ArrayList<QuestionOption>();
                        // 将试题信息添加到数据库
                        try {
                            // 保存试题内容
                            questionService.save(product);

                            // 设置试题选项
                            if (productModelDto.getQuestionOption() != null) {
                                List<String> list = productModelDto.getQuestionOption();
                                for (int l = 0; l < list.size(); l++) {
                                    QuestionOption option = new QuestionOption();
                                    option.setName((char) ('A' + l) + "");
                                    option.setSortNum(l + "");
                                    option.setQuestionId(product.getId());
                                    option.setContent(list.get(l));
                                    options.add(option);

                                }

                            }

                            for (QuestionOption questionOption : options) {
                                // 保存试题选项
                                optionService.save(questionOption);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                }
            } else {
                Msg = "EXCEL文件不能为空！";
                request.getSession().setAttribute("msg", Msg);
                return null;
            }

            questionImportService.save(questionImport);
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
            return null;

        }

        return null;

    }

    /**
     * 保存修改的数据
     * 
     * @param modelMap
     * @param questionImport
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("exam:questionImport:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public String update(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            QuestionImport questionImport) throws Exception {
        if (!beanValidator(modelMap, questionImport)) {
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }
        questionImportService.update(questionImport);
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }

    /**
     * 删除数据库
     * 
     * @param modelMap
     * @param questionImportId
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("exam:questionImport:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public String delete(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, String id)
            throws Exception {
        List<String> listId = Arrays.asList(id.split(","));
        questionImportService.delete(listId);
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }

    /**
     * 假删除
     * 
     * @param modelMap
     * @param questionImport
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("exam:questionImport:delete")
    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @ResponseBody
    public String remove(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            QuestionImport questionImport) throws Exception {
        questionImportService.remove(questionImport);
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }

    /**
     * 试题模版导入
     * 
     * @param session
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/templateImport", method = RequestMethod.POST)
    @ResponseBody
    public String templateImport(@RequestParam(value = "file", required = false) MultipartFile file, HttpSession session,
            HttpServletResponse response, HttpServletRequest request, ModelMap modelMap) {
        List<Map<Question, List<String>>> questionAndOptionsList = new ArrayList<Map<Question, List<String>>>();// 定义试题和答案的map集合对象集
        List<Row> rowList = new ArrayList<Row>();// 定义行对象
        String libraryId = request.getParameter("libraryId");
        if (StringUtils.isEmpty(libraryId)) {
            modelMap.put("message", "未选择题库");
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }
        try {
            rowList = ExcelUtil.getRows(file, 1);
        } catch (Exception e) {
            modelMap.put("message", "解析模版出错");
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }
        int questionNum = rowList.size();// 定义问题数据总条数
        int optionNum = 0;// 定义选项数据总条数
        int addQuestionNum = 0;// 定义新增问题数据条数
        int addOptionNum = 0;// 定义新增选项数据条数
        for (int i = 0; i < rowList.size(); i++) {
            Row row = rowList.get(i);
            Question question = new Question();// 定义试题对象
            List<String> questionOptionList = new ArrayList<String>();// 定义接收所有解析到的试题选项
            int cellNum = row.getLastCellNum();// 获取总列数
            String questionTypeId = null; // 定义转换之后的试题类型
            // 获取所有试题列的值
            String content = ExcelUtil.getStringCellValue(row.getCell(0));// 获取试题内容
            String questionTypeName = ExcelUtil.getStringCellValue(row.getCell(1));// 获取试题类型（拿到的是中文，需要自己转换）
            String answer = ExcelUtil.getStringCellValue(row.getCell(2));// 获取答案
            String analysis = ExcelUtil.getStringCellValue(row.getCell(3));// 获取试题解析
            /*
             * 试题信息非空校验
             */
            if (StringUtils.isEmpty(content)) {
                modelMap.put("message", "导入文件中第" + (i + 2) + "行的试题内容为空");
                RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
                return null;
            }
            if (StringUtils.isEmpty(questionTypeName)) {
                modelMap.put("message", "导入文件中第" + (i + 2) + "行的试题类型为空");
                RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
                return null;
            } else {
                // 解析试题类型为编码
                switch (questionTypeName) {
                case "单选题":
                    questionTypeId = Const.QUESTION_TYPE_ID_SINGLE;
                    break;
                case "多选题":
                    questionTypeId = Const.QUESTION_TYPE_ID_MULTIPLE;
                    break;
                case "判断题":
                    questionTypeId = Const.QUESTION_TYPE_ID_JUDGE;
                    break;
                default:
                    break;
                }
            }
            if (StringUtils.isEmpty(answer)) {
                modelMap.put("message", "导入文件中第" + (i + 2) + "行的答案为空");
                RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
                return null;
            }
            /*
             * 试题信息长度校验
             */
            if (content.length() > 1000) {
                modelMap.put("message", "导入文件中第" + (i + 2) + "行的试题内容长度超出范围");
                RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
                return null;
            }
            if (answer.length() > 200) {
                modelMap.put("message", "导入文件中第" + (i + 2) + "行的答案长度超出范围");
                RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
                return null;
            }
            if (analysis.length() > 500) {
                modelMap.put("message", "导入文件中第" + (i + 2) + "行的试题解析长度超出范围");
                RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
                return null;
            }

            /*
             * 校验通过之后设置question对象
             */
            question.setContent(content);// 设置内容
            question.setQuestionTypeId(questionTypeId);// 设置类型
            question.setAnswer(answer);// 设置答案
            question.setLibraryId(libraryId);// 设置题库
            question.setAnalysis(analysis);// 设置解析
            question.setDelFlag("0");// 设置删除标识（1、为删除0、为未删除）
            /*
             * 开始解析试题答案信息
             */
            for (int j = 4; j < cellNum; j++) {// 定义从第5列开始解析答案信息，第5列之前都时试题信息
                String questionOption = ExcelUtil.getStringCellValue(row.getCell(j));// 获取试题答案选项
                if (!StringUtils.isEmpty(questionOption)) {// 判断试题选项是否为空，如果为空则不存储该选项，也不中断解析之后的选项列
                    questionOptionList.add(questionOption);
                    optionNum++;// 选项总条数
                }
            }
            Map<Question, List<String>> map = new HashMap<Question, List<String>>();
            map.put(question, questionOptionList);
            questionAndOptionsList.add(map);
        }
        for (Map<Question, List<String>> questionAndOptions : questionAndOptionsList) {
            Set set = questionAndOptions.keySet();
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                Question keyQuestion = (Question) iterator.next();
                questionService.save(keyQuestion);// 保存试题信息
                addQuestionNum++;
                List<String> questionOptionsList = questionAndOptions.get(keyQuestion);// 获取该试题所有的选项
                for (int j = 0; j < questionOptionsList.size() && j < 26; j++) {
                    String content = questionOptionsList.get(j);
                    char letterCapital = (char) (j + 65);// 将数字转换成对应的字母
                    QuestionOption questionOption = new QuestionOption();// 定义试题对象
                    questionOption.setContent(content);// 设置选项内容
                    questionOption.setQuestionId(keyQuestion.getId());// 设置试题ID
                    questionOption.setName(String.valueOf(letterCapital));// 设置选项编号（A、B、C...）
                    questionOption.setSortNum(String.valueOf(j));// 设置排序号
                    questionOption.setDelFlag("0");// 设置删除标识（1、为删除0、为未删除）
                    optionService.save(questionOption);// 保存试题对象
                    addOptionNum++;
                }
            }
        }
        modelMap.put("message", "新增问题数据：" + addQuestionNum + "条，失败：" + (questionNum - addQuestionNum) + "条,新增选项数据：" + addOptionNum + "条，失败："
                + (optionNum - addOptionNum) + "条");
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }

    /**
     * 导出Excel数据
     * 
     * @param modelMap
     * @param questionImport
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("exam:questionImport:export")
    @RequestMapping(value = "/export")
    public String export(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            QuestionImport questionImport) throws Exception {
        String fileName = DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
        List<QuestionImport> questionImportList = questionImportService.findAll(questionImport);
        new ExportExcel(null, QuestionImport.class).setDataList(questionImportList).write(response, fileName).dispose();
        return null;
    }
}